// set path here
gl path "~/"

use id year g_ homeowner_g using "$path/Replication/ohio_analysis_local.dta", clear

sort id year

// keep those with variation in homeownership
egen home_mean = mean(homeowner_g), by(id)
drop if home_mean == 0 | home_mean == 1
drop home_mean	

// 
gen switch = 0
replace switch = 1 if (homeowner_g == 1 & homeowner_g[_n-1] == 0) & id == id[_n-1]
gen lag1 = 0
replace lag1 = switch[_n-1] == 1 & id == id[_n-1]
gen lag2 = 0
replace lag2 = lag1[_n-1] == 1 & id == id[_n-1]
gen lag3 = 0
replace lag3 = lag2[_n-1] == 1 & id == id[_n-1]
replace lag3 = 1 if lag3[_n-1] == 1 & id == id[_n-1]
gen lead1 = 0 
replace lead1 = 1 if (switch[_n+1] == 1) & (id == id[_n+1])
gen lead2 = 0 
replace lead2 = 1 if (lead1[_n+1] == 1) & (id == id[_n+1])
gen lead3 = 0 
replace lead3 = 1 if (lead2[_n+1] == 1) & (id == id[_n+1])
gen lead4 = 0 
replace lead4 = 1 if (lead3[_n+1] == 1) & (id == id[_n+1])
gen lead5 = 0 
replace lead5 = 1 if (lead4[_n+1] == 1) & (id == id[_n+1])

compress

reghdfe g_ lag3 lag2 lag1 switch lead1 lead2 lead3 lead4 lead5, a(id year) cluster(id)
local b1 = _b[lag3]
local se1 = _se[lag3]
local b2 = _b[lag2]
local se2 = _se[lag2]
local b3 = _b[lag1]
local se3 = _se[lag1]
local b4 = _b[switch]
local se4 = _se[switch]
local b5 = _b[lead1]
local se5 = _se[lead1]
local b6 = _b[lead2]
local se6 = _se[lead2]
local b7 = _b[lead3]
local se7 = _se[lead3]
local b8 = _b[lead4]
local se8 = _se[lead4]
local b9 = _b[lead5]
local se9 = _se[lead5]

// generate matrix to store coefficients and standard errors
matrix A = J(9,2,.)
mat rownames A = lag3 lag2 lag1 switch lead1 lead2 lead3 lead4 lead5
mat colnames A = b se

forval i = 1(1)9 {
	mat A[`i',1] = `b`i''
	mat A[`i',2] = `se`i''
}

// save matrix
svmat A
keep A*
// rename and label 
rename A1 b
rename A2 se
gen coef = ""
replace coef = "lag3" if _n == 1
replace coef = "lag2" if _n == 2
replace coef = "lag1" if _n == 3
replace coef = "switch" if _n == 4
replace coef = "lead1" if _n == 5
replace coef = "lead2" if _n == 6
replace coef = "lead3" if _n == 7
replace coef = "lead4" if _n == 8
replace coef = "lead5" if _n == 9
// generate axis
gen y = 3
replace y = y[_n-1] - 1 if _n > 1
// compute lower and upper bounds
gen lb = b - 1.96*se
gen ub = b + 1.96*se

scatter b y, xtitle("Local Elections Until Homeownership", size(small)) ///
	ytitle("Effect of Homeownership on Turnout") xlab(-5(1)3) ylab(-0.05(0.05)0.15) ///
	scale(1.3) yline(0) yscale(range(-0.05 0.15)) || rcap lb ub y, legend(off)
	
graph export "$path/Replication/figure2.pdf", replace
graph export "$path/Replication/figure2.eps", replace
